package net.sky.oa.dao.ioffice.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.htsoft.core.web.paging.PagingBean;

import net.sky.oa.dao.SkyBaseDaoImpl;
import net.sky.oa.dao.ioffice.OffSummaryDao;
import net.sky.oa.model.OffSummary;



@SuppressWarnings("unchecked")
@Repository
public class OffSummaryDaoImpl extends SkyBaseDaoImpl<OffSummary> implements OffSummaryDao  {
	
	public OffSummaryDaoImpl() {
		super.setPersistType(OffSummary.class);
	}
	
	public List<OffSummary> findByRusr(int flag,Long rusrId,String title,int type,int sort,Date lasttime,PagingBean pb){
		StringBuilder hql=new StringBuilder("");
		List<OffSummary> myList=new ArrayList<OffSummary>();
		List list=new ArrayList();
		if(flag==1){
			hql.append("from OffSummary sm where sm.user.id=? and sm.status=1");
		}
		
		if(flag==2){
			hql.append("from OffSummary s where s.id in (" +
					"select sm.id from OffSummary sm,OffSummUser su where (sm.id=su.summ.id or (sm.ispublic=1 and sm.status=1)) and su.rusr.id=? ");
		}
		list.add(rusrId);
		try {
			if(StringUtils.isNotEmpty(title))
			{
				hql.append(" and sm.title like ?");
				list.add("%"+title+"%");
			}
			if(type!=-1)
			{
				hql.append(" and sm.type=? ");
				list.add(type);
			}
			if(sort!=-1)
			{
				hql.append(" and sm.sort=?");
				list.add(sort);
			}
			if(null!=lasttime)
			{
				hql.append(" and sm.lasttime=?");
				list.add(lasttime);
			}
			if(flag==1)
				hql.append(" order by sm.id desc");
			else
				hql.append(" group by sm.id) order by s.id desc");
			
			myList=findByHql(hql.toString(),list.toArray(),pb);
				return myList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public OffSummary findById(Long id,Long rusrId,String sort,PagingBean pb){
		StringBuilder sb=new StringBuilder("from OffSummary s where s.id in (select sm from OffSummary sm,OffSummUser su where (sm.id=su.summ.id or (sm.ispublic=1 and sm.status=1)) and su.rusr.id=? and 1=1 ");
		List list=new ArrayList();
		list.add(rusrId);
		try{
			if(StringUtils.isEmpty(sort))
			{
				sb.append(" and sm.id = ?  group by sm.id) ");
			}
			if("asc".equals(sort))
			{
				sb.append(" and sm.id > ?   group by sm.id) order by s.id");
			}
			if("desc".equals(sort))
			{
				sb.append(" and sm.id < ?   group by sm.id) order by s.id desc");
			}			
			list.add(id);
			List<OffSummary> l=findByHql(sb.toString(),list.toArray(),pb);
			if(l.size()>0)
				return l.get(0);
			else
				return null;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
}
